"""
DeepSeek API服务

负责与DeepSeek API的交互，包括故事生成、模型调用等
"""

import os
import time
import asyncio
from typing import Optional, Dict, Any, List
from loguru import logger
import requests
from pydantic import BaseModel

from ..models.story_model import Story, StoryType, Language
from ..models.api_model import StoryRequest, StoryResponse


class DeepSeekConfig(BaseModel):
    """DeepSeek配置模型"""
    api_key: str
    base_url: str = "https://api.deepseek.com"
    model: str = "deepseek-chat"
    max_tokens: int = 4000
    temperature: float = 0.7
    timeout: int = 30


class DeepSeekService:
    """DeepSeek API服务类"""
    
    def __init__(self, config: DeepSeekConfig):
        """
        初始化DeepSeek服务
        
        Args:
            config: DeepSeek配置
        """
        self.config = config
        self.session = requests.Session()
        self.session.headers.update({
            "Authorization": f"Bearer {config.api_key}",
            "Content-Type": "application/json"
        })
        logger.info("DeepSeek服务初始化完成")
    
    async def generate_story(self, request: StoryRequest) -> StoryResponse:
        """
        生成故事
        
        Args:
            request: 故事生成请求
            
        Returns:
            StoryResponse: 故事生成响应
        """
        start_time = time.time()
        
        try:
            # 构建提示词
            prompt = self._build_prompt(request)
            
            # 调用DeepSeek API
            response = await self._call_deepseek_api(prompt, request)
            
            # 解析响应
            story_data = self._parse_story_response(response, request)
            
            # 计算生成时间
            generation_time = time.time() - start_time
            
            # 构建响应
            story_response = StoryResponse(
                success=True,
                message="故事生成成功",
                story_id=story_data.get("story_id"),
                title=story_data.get("title"),
                content_zh=story_data.get("content_zh"),
                content_en=story_data.get("content_en"),
                quality_score=story_data.get("quality_score"),
                generation_time=generation_time
            )
            
            logger.info(f"故事生成成功，耗时: {generation_time:.2f}秒")
            return story_response
            
        except Exception as e:
            logger.error(f"故事生成失败: {str(e)}")
            return StoryResponse(
                success=False,
                message=f"故事生成失败: {str(e)}"
            )
    
    def _build_prompt(self, request: StoryRequest) -> str:
        """
        构建提示词
        
        Args:
            request: 故事生成请求
            
        Returns:
            str: 构建的提示词
        """
        # 基础提示词模板
        base_prompt = """
        你是一个专业的故事创作AI，请根据以下要求创作一个精彩的故事：
        
        故事类型：{story_type}
        语言要求：{language}
        字数限制：{length_limit}字以内
        """
        
        # 根据故事类型添加特定要求
        if request.story_type == StoryType.SHUIHU:
            base_prompt += """
            特殊要求：
            - 基于《水浒传》创作
            - 主人公：{character_name}
            - 风格：诙谐有趣，讲述好汉之间的感情
            - 标题：古诗风格，长度一致，押韵
            - 结构：故事内容 + 教育总结
            - 双语：中英文对照
            """
        
        # 添加通用要求
        base_prompt += """
        创作要求：
        1. 故事要有教育意义和道德启示
        2. 语言生动有趣，适合儿童阅读
        3. 情节完整，结构清晰
        4. 结尾要有总结和启发
        """
        
        # 格式化提示词
        prompt = base_prompt.format(
            story_type=request.story_type.value,
            language="中英文双语" if request.bilingual else "中文",
            length_limit=request.length_limit,
            character_name=request.character_name or "梁山好汉"
        )
        
        return prompt
    
    async def _call_deepseek_api(self, prompt: str, request: StoryRequest) -> Dict[str, Any]:
        """
        调用DeepSeek API
        
        Args:
            prompt: 提示词
            request: 请求参数
            
        Returns:
            Dict[str, Any]: API响应
        """
        payload = {
            "model": self.config.model,
            "messages": [
                {
                    "role": "system",
                    "content": "你是一个专业的故事创作AI，擅长创作有趣、有教育意义的故事。"
                },
                {
                    "role": "user",
                    "content": prompt
                }
            ],
            "max_tokens": self.config.max_tokens,
            "temperature": request.temperature or self.config.temperature,
            "stream": False
        }
        
        try:
            response = self.session.post(
                f"{self.config.base_url}/v1/chat/completions",
                json=payload,
                timeout=self.config.timeout
            )
            response.raise_for_status()
            return response.json()
            
        except requests.exceptions.RequestException as e:
            logger.error(f"DeepSeek API调用失败: {str(e)}")
            raise Exception(f"API调用失败: {str(e)}")
    
    def _parse_story_response(self, api_response: Dict[str, Any], request: StoryRequest) -> Dict[str, Any]:
        """
        解析API响应
        
        Args:
            api_response: API响应
            request: 原始请求
            
        Returns:
            Dict[str, Any]: 解析后的故事数据
        """
        try:
            # 获取生成的文本
            content = api_response["choices"][0]["message"]["content"]
            
            # 解析故事内容
            story_data = self._extract_story_content(content, request)
            
            return story_data
            
        except (KeyError, IndexError) as e:
            logger.error(f"解析API响应失败: {str(e)}")
            raise Exception("解析响应失败")
    
    def _extract_story_content(self, content: str, request: StoryRequest) -> Dict[str, Any]:
        """
        提取故事内容
        
        Args:
            content: 原始内容
            request: 请求参数
            
        Returns:
            Dict[str, Any]: 提取的故事数据
        """
        # 简单的文本分割逻辑
        lines = content.split('\n')
        
        story_data = {
            "title": "",
            "content_zh": "",
            "content_en": "",
            "summary": "",
            "quality_score": 0.8  # 默认质量评分
        }
        
        current_section = ""
        zh_content = []
        en_content = []
        
        for line in lines:
            line = line.strip()
            if not line:
                continue
                
            # 检测标题
            if line.startswith('#') or line.startswith('标题'):
                story_data["title"] = line.replace('#', '').replace('标题：', '').strip()
                continue
            
            # 检测中文内容
            if '中文版' in line or 'Chinese' in line:
                current_section = "zh"
                continue
                
            # 检测英文内容
            if 'English' in line or '英文版' in line:
                current_section = "en"
                continue
                
            # 检测总结
            if '总结' in line or 'Summary' in line:
                current_section = "summary"
                continue
            
            # 根据当前部分添加内容
            if current_section == "zh":
                zh_content.append(line)
            elif current_section == "en":
                en_content.append(line)
            elif current_section == "summary":
                story_data["summary"] += line + "\n"
        
        # 合并内容
        story_data["content_zh"] = "\n".join(zh_content)
        if request.bilingual:
            story_data["content_en"] = "\n".join(en_content)
        
        return story_data
    
    async def batch_generate_stories(self, requests: List[StoryRequest]) -> List[StoryResponse]:
        """
        批量生成故事
        
        Args:
            requests: 故事生成请求列表
            
        Returns:
            List[StoryResponse]: 故事生成响应列表
        """
        results = []
        
        for i, request in enumerate(requests):
            logger.info(f"正在生成第 {i+1}/{len(requests)} 个故事")
            
            try:
                response = await self.generate_story(request)
                results.append(response)
                
                # 添加延迟避免API限制
                if i < len(requests) - 1:
                    await asyncio.sleep(1)
                    
            except Exception as e:
                logger.error(f"批量生成第 {i+1} 个故事失败: {str(e)}")
                results.append(StoryResponse(
                    success=False,
                    message=f"生成失败: {str(e)}"
                ))
        
        return results
    
    async def test_connection(self) -> bool:
        """
        测试API连接
        
        Returns:
            bool: 连接是否成功
        """
        try:
            payload = {
                "model": self.config.model,
                "messages": [
                    {
                        "role": "user",
                        "content": "Hello"
                    }
                ],
                "max_tokens": 10
            }
            
            response = self.session.post(
                f"{self.config.base_url}/v1/chat/completions",
                json=payload,
                timeout=10
            )
            response.raise_for_status()
            
            logger.info("DeepSeek API连接测试成功")
            return True
            
        except Exception as e:
            logger.error(f"DeepSeek API连接测试失败: {str(e)}")
            return False 